<?php


namespace App\Helpers;

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

/**
 * 邮件助手类
 *
 * Class EmailHelper
 *
 * @package App\Helpers
 * @author  kingsg
 */
class EmailHelper extends Helper
{
	private static $initFlag = false;
	private static $host;
	private static $username;
	private static $password;
	private static $fromAddress;
	private static $fromUser;
	private static $ccAddress;

	/**
	 * 初始化配置
	 */
	private static function initConfig()
	{
		if (static::$initFlag === false) {
			static::$host        = config('library.sendMail.host');
			static::$username    = config('library.sendMail.username');
			static::$password    = config('library.sendMail.passwd');
			static::$fromAddress = config('library.sendMail.from_address');
			static::$fromUser    = config('library.sendMail.from_user');
			static::$ccAddress   = config('library.sendMail.cc_address');

			static::$initFlag = true;
		}
	}


	/**
	 * 发送邮件
	 *
	 * @param array  $address
	 * @param string $subject
	 * @param string $content
	 * @param array  $attachment
	 */
	public static function sendMail(array $address, string $subject, string $content, array $attachment = [])
	{
		// 初始化配置
		static::initConfig();
		//Create an instance; passing `true` enables exceptions
		$mail = new PHPMailer(true);
		try {
			//Server settings
			$mail->SMTPDebug = SMTP::DEBUG_SERVER;
			$mail->isSMTP();
			$mail->CharSet    = 'UTF-8'; //设置邮件的字符编码
			$mail->Encoding   = "base64";
			$mail->Host       = static::$host;
			$mail->SMTPAuth   = true;
			$mail->Username   = static::$username;
			$mail->Password   = static::$password;
			$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
			$mail->Port       = 465;

			//Recipients
			$mail->setFrom(static::$fromAddress, static::$fromUser);
//			$mail->addAddress(static::$fromAddress, static::$fromUser);     //Add a recipient
			foreach ($address as $value) {
				$mail->addAddress($value);
			}

			$mail->addReplyTo(static::$fromAddress, static::$fromUser);
			$mail->addCC(static::$ccAddress); // 抄送
			//$mail->addBCC('bcc@example.com');

			// 添加附件
			if (!empty($attachment)) {
				foreach ($attachment as $value) {
					$mail->addAttachment($value);
				}
			}
			//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

			//Content
			$mail->isHTML(true);                                  //Set email format to HTML
			$mail->Subject = $subject;
			$mail->Body    = $content;
			$mail->AltBody = $content;


			$mail->send();
		} catch (Exception $ex) {
			LogHelper::exLog($ex, 'email');
		}
	}
}